import React, { useState, useEffect, useMemo, useContext, useRef } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button,
  Space,
  Popover,
  Checkbox,
  Modal,
  Message,
  Typography,
  Dropdown,
  Menu,
} from '@arco-design/web-react';
import {
  IconDownload,
  IconFilter,
  IconPlus,
} from '@arco-design/web-react/icon';
import cs from 'classnames';
import useLocale from '@/utils/useLocale';
import SearchForm from './form';
import locale from './locale';
import styles from './style/index.module.less';
import { getColumns } from './constants';
import { GlobalContext } from '@/context';
import { Active, Delete, Export, Search } from '@/api/modules/entity';
import Create from './create';
import ActionWrapper from '@/components/ActionWrapper';
import { EntityCreate } from '@/api/interface/entity';
import useIsMountedRef from '@/utils//useIsMountedRef';
import useStorageJson from '@/utils/useStorageJson';
import { useSelector } from 'react-redux';
import { GlobalState } from '@/store';
import debounce from 'lodash/debounce';
import has from 'lodash/has';
import { SorterInfo } from '@arco-design/web-react/es/Table/interface';
import { useDownload } from '@/utils/useDownload';
const { Title } = Typography;

function Entities() {
  const t = useLocale(locale);
  const { rtl, lang } = useContext(GlobalContext);
  const { userInfo } = useSelector((state: GlobalState) => state);
  const [tableColumns, setTableColumns] = useStorageJson(
    `${userInfo.id}_entities_tableColumns`,
    [
      'id',
      'name',
      'nameAr',
      'emirate',
      'action',
      'active',
      'shareholdingPercentage',
      'chairman',
      'attachments',
    ]
  );
  const options: any = [
    {
      label: t['searchTable.columns.number'],
      value: 'id',
      width: 60,
    },
    {
      label: t['searchTable.columns.nameEn'],
      value: 'name',
      width: 220,
    },
    {
      label: t['searchTable.columns.nameAr'],
      value: 'nameAr',
      width: 180,
    },
    {
      label: t['searchTable.columns.emirate'],
      value: 'emirate',
      width: 120,
    },

    {
      label: t['searchTable.columns.ShareholdingPercentage'],
      value: 'shareholdingPercentage',
      width: 230,
    },
    {
      label: t['searchTable.columns.ChairmanName'],
      value: 'chairman',
      width: 140,
    },
    {
      label: t['searchTable.columns.Attachments'],
      value: 'attachments',
      width: 220,
    },
    {
      label: t['searchTable.columns.active'],
      value: 'active',
      width: 100,
    },
    {
      label: t['searchTable.columns.action'],
      value: 'action',
      width: 100,
    },
  ];

  // 刷新
  const [visible, setVisible] = useState(false);
  const onVisible = (status: boolean, refresh?: boolean) => {
    setVisible(status);
    if (refresh) {
      if (pagination.current === 1) {
        fetchData();
        return;
      }
      setPatination((e) => ({ ...e, current: 1 }));
    }
  };

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeOptions: [10, 20, 50, 100],
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(false);
  const [formParams, setFormParams] = useState<any>();
  const isMountedRef = useIsMountedRef();
  useEffect(() => {
    if (!formParams) {
      return;
    }
    console.log(formParams);
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  async function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    try {
      const { data } = await Search({
        pageNo: current,
        pageSize,
        ...formParams,
      });
      if (isMountedRef.current) {
        setData(data.data);
        setPatination((e) => ({ ...e, current, pageSize, total: data.count }));

        setLoading(false);
      }
    } catch (e) {
      setLoading(false);
    }
  }

  function onChangeTable({ current, pageSize }, sorter: SorterInfo) {
    const { direction, field } = sorter;
    if (direction) {
      const sort = [];
      const obj = Object.create({});
      if (field == 'name') {
        obj.field = 'name';
      }
      obj.asc = direction == 'ascend';
      sort.push(obj);
      setFormParams({ ...formParams, sort });
    } else {
      const updatedFormParams = { ...formParams, sort: undefined };
      delete updatedFormParams.sort;
      setFormParams(updatedFormParams);
    }
    setPatination((e) => ({
      ...e,
      current,
      pageSize,
    }));
  }

  const handleSearch = debounce((params) => {
    if (has(params, 'active')) {
      params.active =
        params.active === 1 ? true : params.active === 0 ? false : '';
    }
    setPatination((e) => ({ ...e, current: 1 }));
    setFormParams(params);
  }, 300);

  const CheckboxGroup = Checkbox.Group;

  const tableColumnsFilter = () => (
    <CheckboxGroup
      direction="vertical"
      options={options.map((a) => {
        let disabled = false;
        if (tableColumns.length === 1) {
          disabled = tableColumns.includes(a.value);
        }

        return { ...a, disabled };
      })}
      value={tableColumns}
      key={lang}
      onChange={(value) => {
        if (value.length < 1) {
          return;
        }
        setTableColumns(value);
      }}
    />
  );

  const [modalStatus, setMldalStatus] = useState<boolean>(false);
  const [modalLoading, setModalLoading] = useState<boolean>(false);
  const [record, setRecord] = useState<EntityCreate>({
    id: '',
    emirate: '',
    name: '',
    nameAr: '',
    reference: '',
    shareholdingPercentage: '',
    active: false,
    attachments: [],
    chairman: '',
  });
  const tableCallback = async (record: any, type: string) => {
    if (type === 'editActive') {
      setMldalStatus(true);
      setRecord(record);
      return;
    }
    if (type === 'edit') {
      setRecord(record);
      setVisible(true);
      return;
    }
  };

  const columns = useMemo(
    () => getColumns(t, tableCallback, tableColumns, options, lang),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [t, tableColumns]
  );
  const width = useMemo(
    () => {
      return columns.reduce((sum, { width = 0 }) => sum + width, 0) || 0;
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [columns]
  );

  async function ExportExcel(e: number) {
    const params = {
      ...formParams,
      fields: tableColumns,
    };
    await useDownload(
      Export,
      lang === 'ar-EG' ? 'الجهات' : 'Entities',
      lang === 'ar-EG' ? 'ar' : 'en',
      e,
      e === 1 ? '.csv' : '.xlsx',
      params
    );
  }
  return (
    <Card>
      {/* <Title heading={6} className={styles['page-title']}>
        {t['searchTable.form.title']}
      </Title> */}
      <SearchForm onSearch={handleSearch} />

      <Create visible={visible} onVisible={onVisible} record={record} />
      <div className={cs(styles['button-group'], rtl ? 'rtl' : '')}>
        <Space>
          <ActionWrapper action="entities.entity/create">
            <Button
              type="primary"
              icon={<IconPlus />}
              onClick={() => {
                setRecord({
                  emirate: '',
                  name: '',
                  nameAr: '',
                  reference: '',
                  shareholdingPercentage: '',
                  active: false,
                  attachments: [],
                  chairman: '',
                }),
                  setVisible(true);
              }}
            >
              {t['searchTable.operations.add']}
            </Button>
          </ActionWrapper>
        </Space>
        <Space>
          <Popover
            position="bottom"
            trigger="click"
            content={tableColumnsFilter}
          >
            <Button icon={<IconFilter />}>
              {t['searchTable.operation.filter']}
            </Button>
          </Popover>
          <Dropdown
            droplist={
              <Menu>
                <Menu.Item
                  key="1"
                  className={styles['export-text']}
                  onClick={() => ExportExcel(1)}
                >
                  CSV
                </Menu.Item>
                <Menu.Item
                  key="2"
                  className={styles['export-text']}
                  onClick={() => ExportExcel(2)}
                >
                  Excel
                </Menu.Item>
              </Menu>
            }
            position="bottom"
          >
            <Button type="primary" icon={<IconDownload />}>
              {t['searchTable.operation.export']}
            </Button>
          </Dropdown>
        </Space>
      </div>
      <Table
        border={{
          wrapper: true,
          cell: true,
        }}
        scroll={{
          x: width,
        }}
        hover={true}
        rowKey="id"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
      />

      <Modal
        confirmLoading={modalLoading}
        closable
        style={{ width: '760px' }}
        className={cs(rtl ? 'rtl' : '')}
        title={
          <>
            {record.active
              ? t['modal.deactivate.title']
              : t['modal.activate.title']}
            <span style={{ fontWeight: 'bold', color: '#ff4000' }}>
              {'  '}
              {record.name}({record.nameAr})
            </span>
            {lang == 'en-US' ? '?' : '؟'}
          </>
        }
        visible={modalStatus}
        simple
        okText={record.active ? t['modal.deactivate'] : t['modal.activate']}
        onOk={() => {
          setModalLoading(true);
          Active({ id: record.id, active: record.active ? false : true })
            .then(() => {
              Message.success(
                record.active
                  ? t['modal.deactivate.success']
                  : t['modal.activate.success']
              );
              setMldalStatus(false);
              setModalLoading(false);
              fetchData();
            })
            .catch(() => {
              setModalLoading(false);
            });
        }}
        onCancel={() => {
          setMldalStatus(false);
        }}
      >
        <div className={styles['modal-content']}>
          <div className={cs(rtl ? 'text-right' : '')}>
            {record.active
              ? t['modal.deactivate.content']
              : t['modal.activate.content']}
            :
          </div>
          <div className={cs(rtl ? 'text-right' : '')}>
            -{' '}
            {record.active
              ? t['modal.deactivate.desc']
              : t['modal.activate.desc']}
            .
          </div>
          <div className={cs(rtl ? 'text-right' : '')}>
            -
            {record.active
              ? t['modal.deactivate.desc1']
              : t['modal.activate.desc1']}
            .
          </div>
        </div>
      </Modal>
    </Card>
  );
}

export default Entities;
